import urllib.request
import json


def baidu_transform(url, json_data):
    """
    发送post请求
    :param url:api接口
    :param json_data:body中的数据
    :return:
    """
    req = urllib.request.Request(url)
    req.add_header('Content-Type', 'application/json')
    res = urllib.request.urlopen(req, json.dumps(json_data).encode())
    return res.read().decode('gbk').encode('utf-8')


# client_id 为官网获取的自己创建的应用的AK， client_secret 为官网获取的自己创建的应用的SK，参考地址：http://ai.baidu.com/docs#/Auth/top
ak = 'B5fOnnkn9WP1le2xONcoPN8G'
sk = 'aPzajIGfydjkysmCqeGtu6EScmb6oG5N'

host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s' \
       '&client_secret=%s' % (ak, sk)
request = urllib.request.Request(host)
request.add_header('Content-Type', 'application/json; charset=UTF-8')
response = urllib.request.urlopen(request)
content = response.read()

access_token = ''
if content:
    access_token = json.loads(content)['access_token']
else:
    print('获取access token 失败')


ecnet = 'https://aip.baidubce.com/rpc/2.0/nlp/v1/ecnet?access_token=%s' % access_token
data = {
    "text": "我要去学校学系"
}
